<template>
  <view class="profile-container">
    <!-- 用户头像和基本信息组件 -->
    <ProfileHeader 
      :userInfo="userInfo"
      :isLoggedIn="isLoggedIn"
      :userPoints="userPoints"
      :userLevel="userLevel"
      :levelProgress="levelProgress"
      @avatar-click="handleAvatarClick"
      @avatar-error="handleAvatarError"
      @settings-click="navigateToSettings"
    />
    
    <!-- 用户统计卡片组件 -->
    <UserStatsCards 
      :userStats="userStats"
      :userPoints="userPoints"
      @backpack-click="navigateToBackpack"
      @points-click="goToPoints"
    />
    
    <!-- 功能模块组件 -->
    <FunctionModules 
      :isCheckedIn="checkInStatus"
      @checkin="handleCheckIn"
      @navigate="navigateToPage"
    />
    
    <!-- 最近活动已移至接口日志页面 -->
    
    <!-- 操作按钮组件 -->
    <ActionButtons 
      :isLoggedIn="isLoggedIn"
      @login="handleAvatarClick"
      @logout="logout"
    />
    
    <!-- 签到成功弹窗 -->
    <ToastNotification 
      :visible="showCheckInSuccess" 
      title="签到成功"
      :message="`+${checkInPoints} 积分`"
      type="success"
      icon="✨"
      @close="showCheckInSuccess = false"
    />
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import pointsManager from '@/utils/points-manager.js'
import chatService from '@/utils/websocket-chat-service.js'
import toastHelper from '@/utils/toast-helper.js'
import ProfileHeader from './components/ProfileHeader.vue'
import UserStatsCards from './components/UserStatsCards.vue'
import FunctionModules from './components/FunctionModules.vue'
import ToastNotification from '@/components/ToastNotification.vue'

import ActionButtons from './components/ActionButtons.vue'

export default {
  components: {
    ProfileHeader,
    UserStatsCards,
    FunctionModules,
    ActionButtons,
    ToastNotification
  },
  data() {
    return {
      userInfo: {
        id: '',
        name: '',
        email: '',
        phone: '',
        birthday: '',
        bio: '',
        avatar: '',
        created_at: '',
        role: 'user'
      },
      userStats: {
        loginDays: 0,
        achievements: 0
      },
      userPoints: 0,
      userLevel: 1,
      levelProgress: 0,
      isLoggedIn: false,
      checkInStatus: false,
      showCheckInSuccess: false,
      checkInPoints: 0
    }
  },
  
  onLoad() {
    this.loadUserInfo()
    this.loadPointsData()
    this.loadUserStats()
    this.checkLoginStatus()
  },
  
  onShow() {
    this.checkLoginStatus()
    // 检查登录状态后再加载数据，确保使用正确的用户ID
    if (this.isLoggedIn) {
      this.loadUserInfo()
      this.loadPointsData()
      this.loadUserStats()
    } else {
      this.resetUserData()
    }
  },
  
  methods: {
    // 加载用户信息
    loadUserInfo() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (currentUser) {
          const userData = JSON.parse(currentUser)
          this.userInfo = { ...this.userInfo, ...userData }
          this.isLoggedIn = true
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
      }
    },
    
    // 加载积分数据
    loadPointsData() {
      try {
        const pointsData = pointsManager.getPointsData()
        if (pointsData) {
          this.userPoints = pointsData.points || 0
          this.userLevel = pointsData.level || 1
          this.levelProgress = pointsData.levelProgress || 0
          // 使用 getCheckInStatus() 方法，会自动检查日期并重置
          this.checkInStatus = pointsManager.getCheckInStatus()
        } else {
          this.initDefaultPointsData()
        }
      } catch (error) {
        console.error('加载积分数据失败:', error)
        this.initDefaultPointsData()
      }
    },
    
    // 加载用户统计
    loadUserStats() {
      try {
        if (this.userInfo.created_at) {
          const createdDate = new Date(this.userInfo.created_at)
          const currentDate = new Date()
          const timeDiff = currentDate.getTime() - createdDate.getTime()
          const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
          this.userStats.loginDays = Math.max(1, daysDiff)
        } else {
          this.userStats.loginDays = 1
        }
      } catch (error) {
        console.error('加载用户统计失败:', error)
        this.userStats.loginDays = 1
      }
    },
    
    // 初始化默认积分数据
    initDefaultPointsData() {
      // 检查是否已登录
      const token = uni.getStorageSync('user_token')
      if (!token) {
        // 未登录时初始化空数据
        this.userPoints = 0
        this.userLevel = 1
        this.levelProgress = 0
        this.checkInStatus = false
        this.recentActivities = []
        return
      }
      
      this.userPoints = 100
      this.userLevel = 1
      this.levelProgress = 0
      this.checkInStatus = false
      this.recentActivities = [{
        id: 1,
        icon: '🎉',
        title: '欢迎加入',
        time: '刚刚',
        points: 100,
        type: 'earn'
      }]
      pointsManager.savePointsData({
        points: this.userPoints,
        level: this.userLevel,
        levelProgress: this.levelProgress,
        checkInStatus: this.checkInStatus,
        recentActivities: this.recentActivities
      })
    },
    
    // 添加积分
    addPoints(points, reason = '获得积分') {
      const success = pointsManager.addPoints(points, reason)
      if (success) {
        this.loadPointsData()
      }
    },
    
    // 检查登录状态
    checkLoginStatus() {
      try {
        const token = uni.getStorageSync('user_token')
        const currentUser = uni.getStorageSync('currentUser')
        const wasLoggedIn = this.isLoggedIn
        
        if (token && currentUser) {
          this.isLoggedIn = true
          // 如果登录状态从 false 变为 true，或者用户切换了账号，需要刷新数据
          if (!wasLoggedIn || this.hasUserChanged()) {
            this.loadUserInfo()
            this.loadPointsData()
            this.loadUserStats()
          }
        } else {
          this.isLoggedIn = false
          this.resetUserData()
        }
      } catch (error) {
        console.error('检查登录状态失败:', error)
        this.isLoggedIn = false
        this.resetUserData()
      }
    },
    
    // 检查用户是否切换了账号
    hasUserChanged() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) return false
        
        const user = JSON.parse(currentUser)
        const newUserId = user.id || user.email
        const oldUserId = this.userInfo.id || this.userInfo.email
        
        return newUserId && oldUserId && newUserId !== oldUserId
      } catch (error) {
        return false
      }
    },
    
    // 处理头像加载错误
    handleAvatarError() {
      this.userInfo.avatar = ''
    },
    
    // 每日签到
    handleCheckIn() {
      // 检查登录状态
      if (!this.isLoggedIn) {
        toastHelper.showError('请先登录后再签到')
        return
      }
      
      // 使用pointsManager检查签到状态，支持每日重置
      if (pointsManager.getCheckInStatus()) {
        toastHelper.showError('今日已签到')
        return
      }
      
      this.checkInStatus = true
      pointsManager.setCheckInStatus(true)
      // 直接使用pointsManager.addPoints，避免重复调用
      pointsManager.addPoints(10, '每日签到')
      this.loadPointsData() // 重新加载数据
      
      // 显示签到成功弹窗
      this.showCheckInSuccess = true
      this.checkInPoints = 10
    },
    
    // 导航方法
    goToPoints() {
      uni.navigateTo({ url: '/pages/points/points' })
    },
    
    navigateToGameCenter() {
      uni.navigateTo({ url: '/pages/game/list/list' })
    },
    
    navigateToPage(url) {
      uni.navigateTo({ url: url })
    },
    
    navigateToBackpack() {
      uni.navigateTo({ url: '/pages/user/backpack/backpack' })
    },
    
    navigateToSettings() {
      uni.navigateTo({ url: '/pages/settings/settings' })
    },
    
    // 处理头像点击
    handleAvatarClick() {
      if (!this.isLoggedIn) {
        uni.navigateTo({ url: '/pages/auth/login/login' })
      }
    },

    // 退出登录
    logout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出当前账户吗？',
        success: (res) => {
          if (res.confirm) {
            this.performLogout()
          }
        }
      })
    },

    // 执行退出登录
    async performLogout() {
      try {
        try {
          await chatService.disconnect()
          console.log('WebSocket连接已断开')
        } catch (error) {
          console.warn('断开WebSocket连接失败:', error)
        }
        
        // 记录退出时间（在清除 token 之前）
        const goldManagerModule = await import('@/utils/gold-manager.js')
        const goldManager = goldManagerModule.default || goldManagerModule
        if (goldManager && typeof goldManager.recordLogoutTime === 'function') {
          goldManager.recordLogoutTime()
        }
        
        const keysToRemove = [
          'user_token', 'currentUser', 'currentToken', 'isServerLogin',
          'user_info', 'user_settings', 'friends_list', 'chat_messages',
          'friend_requests', 'last_sync_time', 'sync_history',
          'offline_user_data', 'local_chat_data', 'notification_settings'
        ]
        
        keysToRemove.forEach(key => {
          try {
            uni.removeStorageSync(key)
          } catch (error) {
            console.log(`清除存储项 ${key} 失败:`, error)
          }
        })
        
        this.clearStorageByPrefix('friend_requests_')
        this.clearStorageByPrefix('friends_list_')
        this.clearStorageByPrefix('chat_')
        
        // 清除当前用户的积分数据
        pointsManager.clearAllUsersData()
        
        this.resetUserData()
        
        uni.showToast({ title: '已退出登录', icon: 'success', duration: 1500 })
        
        // 保留在当前页面，不强制跳转
        // 延迟刷新页面数据
        setTimeout(() => {
          // 如果当前在个人中心页面，刷新数据即可
          // 如果不在个人中心，返回上一页
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1]
          if (currentPage && currentPage.route === 'pages/user/profile/profile') {
            // 在个人中心页面，刷新数据
            this.loadUserInfo()
            this.loadPointsData()
            this.checkLoginStatus()
          } else {
            // 不在个人中心，返回上一页（如果上一页存在）
            if (pages.length > 1) {
              uni.navigateBack()
            } else {
              // 没有上一页，跳转到首页
              uni.reLaunch({ url: '/pages/index/index' })
            }
          }
        }, 1500)
        
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.showToast({ title: '退出登录失败', icon: 'error' })
      }
    },

    // 按前缀清除存储
    clearStorageByPrefix(prefix) {
      try {
        const storageInfo = uni.getStorageInfoSync()
        if (storageInfo && storageInfo.keys) {
          storageInfo.keys.forEach(key => {
            if (key.startsWith(prefix)) {
              uni.removeStorageSync(key)
            }
          })
        }
      } catch (error) {
        console.log('按前缀清除存储失败:', error)
      }
    },

    // 重置用户数据
    resetUserData() {
      this.isLoggedIn = false
      this.userInfo = {
        id: '', name: '', email: '', phone: '',
        birthday: '', bio: '', avatar: '', created_at: '', role: 'user'
      }
      this.userStats = { loginDays: 0, achievements: 0 }
      this.userPoints = 0
      this.userLevel = 1
      this.levelProgress = 0
      this.checkInStatus = false
      this.recentActivities = []
    }
  }
}
</script>

<style scoped>
/* ========== 主容器样式 ========== */
.profile-container {
  min-height: calc(100vh - 100rpx);
  background: linear-gradient(180deg, #f7f8fc 0%, #eef1f7 100%);
  padding: 20rpx;
  padding-bottom: 40rpx;
}
</style>
